/*
 * Programa
 */

#include"ParserParametros.h"
#include "utiles.h"
#include "Base64.h"



int main(int argc,char** argv){
	FILE *f1,*f2;
	int continuar,eof1,eof2;
	int readSize;
	char *buffer,*file1,*file2;
	char op;
	char returnString[5];
	short maxima_linea = 0;        
	int errno = 0;
	f1=f2=NULL;
	file1=file2=NULL;
	op = END_OF_STRING;
	readSize = 0;
	returnString[5] = '\0';

	eof1=eof2=0;
	continuar=1;
	buffer=NULL;
	convertirEntrada(argc,argv,&op,&file1,&file2);

	//If no operation is set exit
	if(op == END_OF_STRING){
		printf(ERROR_PARAMETROS);
		return -1;
	}




	if (abrirArchivos(argc,argv,&f1,&f2,file1,file2) < 0)
		return -1;

	while(continuar){

		switch (op) {
			case 'e':
				eof1=readEncode(f1,&buffer);
				break;
			case 'd':
				eof1=readDecode(f1,&buffer);
				break;
		}
		//Obtengo la clave valor del archivo 1

		if (eof1 ==EOF) {
			free(buffer);
			continuar=0;
			continue;
		}

		//Make the operation, encode or decode
		int sizeDecoded=0;
		switch (op) {
			case 'e':
				errno = b64_encode(returnString,buffer,eof1);

				if(maxima_linea == 76){
					maxima_linea = 0;
					fprintf(f2,"%s"," ");
				}

				fwrite(returnString,sizeof(char) * 4,1,f2);
				break;
			case 'd':
				errno = b64_decode(returnString,buffer,eof1,&sizeDecoded);
				fwrite(returnString,sizeof(char) * sizeDecoded,1 ,f2);
				break;
		}

		free(buffer);
		buffer = NULL;


		if(errno == B64_CHARACTER_INVAL){
			fprintf(stderr,"%s","\nHubo un caracter invalido...\nFin del proceso\n");
			exit(-1);
		}

		maxima_linea += 4;
	}

	fclose(f1);
	fclose(f2);

	return 0;

}

